package kuangshen.syn;

/**
 * @program: liangt
 * @description: 多线程测试买票
 * @author: liangt
 * @create: 2021-03-03 14:41
 */
/**
 * 线程不安全，有负数
 * 我拿到10
 * 她拿到9
 * 他拿到8
 * 我拿到7
 * 他拿到6
 * 她拿到6
 * 我拿到5
 * 她拿到4
 * 他拿到3
 * 我拿到2
 * 她拿到1
 * 他拿到0
 * 我拿到-1
 */

public class UnSynBuyTicket {

    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket,"我").start();
        new Thread(buyTicket,"他").start();
        new Thread(buyTicket,"她").start();
    }

}

class BuyTicket implements Runnable{
    private int ticketNumbers = 10;
    boolean falg = true;
    @Override
    public void run() {
        while (true){
            buy();
        }
    }

    public synchronized void buy() {
        if (ticketNumbers <= 0){
            falg = false;
            return;
        }
        //模拟延时
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNumbers--);
    }
}
